<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/2
 * Time: 16:38
 */

namespace app\admin\controller;


use app\service\PrizeService;
use think\Controller;
use think\Db;
use think\Session;

class Prize extends Common
{
    /**
     * @return array|mixed
     * @context 创建奖品
     */
    function create()
    {
        if (input("get.action") == "create") {
            $param = input("post.");
            if($param['active_id']=='undefined'){
                $param['active_id']=0;
            }
            $mark = $param['mark'];
            unset($param['mark']);
            $param['storage'] = "SS";
            if (!isset($param['voucher_id'])) {
                $param['voucher_id'] = 0;
                $param['validity_period'] = 0;
                $param['voucher_title'] = "";

            }
            if (!isset($param['worth'])) {
                $param['worth'] = 0;
                $param['detail'] = NULL;
            }
            if($mark==1 or $mark==2 or $mark==3){
                $list = Session("prize_" . $mark);
                if (empty($list)) {
                    $list = array($param);
                } else {
                    array_push($list, $param);
                }
                Session("prize_" . $mark, $list);
            }else{
                Db::table("active_reward")->insert(array("active_id"=>$param['active_id'],"category"=>$param['category'],"title"=>$param['title'],
                    "reward_num"=>$param['reward_num'],"stock_num"=>$param['stock_num'],"unit"=>$param['unit'],"reward_rate"=>$param['reward_rate'],
                    "reward_times"=>$param['reward_times'],"validity_period"=>$param['validity_period'],"voucher_id"=>$param['voucher_id'],
                    "worth"=>$param['worth'],"detail"=>$param['detail'],"active_category"=>$mark));
            }

            return array("status" => true);
        } else {
            $this->assign("mark", input("get.mark"));
            $this->assign("type", input("get.type"));
            # 签到需要的字段
            $this->assign("active_id",input("get.active_id"));
            return $this->fetch();
        }
    }

    /**
     * @return array
     * @context 获取奖品列表
     */
    function getsPrizeList()
    {
        $mark = input("post.mark");
        $list = Session("prize_" . $mark);
        if (!empty($list)) {
            $str = "<label class=\"layui-form-label\">奖品列表</label>
        <div class=\"layui-input-block\">
            <table class=\"layui-table layui-form\">
                <thead>
                    <tr>
                        <th>奖品名称</th>
                        <th>奖品类型</th>
                        <th>奖励数量</th>
                        <th>上架数量</th>";
            if($mark!=2 and $mark!=4){
                $str.="
                        <th>单位</th>
                        <th>获奖概率</th>
                        <th>单人中奖次数</th>";
            }
            $str.="
                        <th>卡券名称</th>
                        <th>卡券有效期</th>";
            if($mark!=2 and $mark!=4){
                $str.="
                        <th>价值</th>
                        <th>奖品说明</th>";
            }
            $str.="
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>";
            foreach ($list as $k => $v) {
                $str .= "
                    <tr>
                        <td>{$v['title']}</td>
                        <td>" . getsPrizeCategory($v['category']) . "</td>
                        <td style='cursor: pointer' ondblclick='changePrizeInfo(this,\"{$k}\",\"{$v['id']}\",\"{$mark}\",\"{$v['storage']}\",\"reward_num\",\"1\")' data-param='{$v['reward_num']}'>{$v['reward_num']}</td>
                        <td style='cursor: pointer' ondblclick='changePrizeInfo(this,\"{$k}\",\"{$v['id']}\",\"{$mark}\",\"{$v['storage']}\",\"stock_num\",\"1\")' data-param='{$v['stock_num']}'>{$v['stock_num']}</td>
                        ";
                if($mark!=2 and $mark!=4){
                    $str.="<td>{$v['unit']}</td>
                        <td style='cursor: pointer' ondblclick='changePrizeInfo(this,\"{$k}\",\"{$v['id']}\",\"{$mark}\",\"{$v['storage']}\",\"reward_rate\",\"2\")' data-param='{$v['reward_rate']}'>{$v['reward_rate']}</td>
                        <td style='cursor: pointer' ondblclick='changePrizeInfo(this,\"{$k}\",\"{$v['id']}\",\"{$mark}\",\"{$v['storage']}\",\"reward_times\",\"1\")' data-param='{$v['reward_times']}'>{$v['reward_times']}</td>
                       ";
                }
                $str.=" <td>{$v['voucher_title']}</td>
                        <td>{$v['validity_period']}</td>";
                if($mark!=2 and $mark!=4){
                    $str.="<td>{$v['worth']}</td>
                        <td>{$v['detail']}</td>";
                }
                $str.="
                        <td><button class=\"layui-btn layui-btn-sm layui-btn-danger data-delete-btn\" onclick='deletePrize(this,\"{$k}\",\"{$mark}\",\"{$v['storage']}\",\"{$v['id']}\")'> 删除</button></td>
                    </tr>";
            }
            $str .= "
                </tbody>
            </table>
        </div>";
            return array("status" => true, "data" => $str);
        } else {
            return array("status" => false);
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 删除奖品
     */
    function deletePrize()
    {
        $id = input("post.id");
        $mark = input("post.mark");
        $storage = input("post.storage");
        if($storage=="DBSIGN"){
            $db_id=input("post.db_id");
            Db::table("active_reward")->where(array("id"=>$db_id))->delete();
        }else{
            # session删除
            $list = Session("prize_" . $mark);
            unset($list[$id]);
            Session("prize_" . $mark, ($list));
        }
        return array("status" => true);
    }

    /**
     * @param $mark
     * @return bool
     * @context 清空奖品缓存
     */
    function clearPrizeStorage($mark)
    {
        Session("prize_" . $mark, null);
        return true;
    }

    /**
     * @param $mark
     * @return mixed
     * @context 获取奖品缓存
     */
    function getsPrizeStorage($mark)
    {
        return Session("prize_" . $mark);
    }

    /**
     * @param $active_id
     * @param $type
     * @param $mark
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 将数据库中的奖品赋值给缓存
     */
    function setPrizeStorage($active_id, $type, $mark)
    {
        # 活动奖品
        $list = Db::table("active_reward ar")
            ->field("ar.*,vo.title voucher_title,vo.price voucher_price")
            ->join("voucher vo", "ar.voucher_id=vo.id and ar.category=3", "left")
            ->where(array("ar.active_id" => $active_id, "ar.active_category" => $type))
            ->select();
        $_array = array("storage" => "DB");
        array_walk($list, function (&$value, $key, $_array) {
            $value = array_merge($value, $_array);
        }, $_array);
        Session("prize_" . $mark, $list);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 大转轮获取卡券列表
     */
    function getsPrizeVoucherList()
    {
        return PrizeService::prizeVoucher();
    }

    /**
     * @return array
     * @context 改变奖品信息提交
     */
    function confirmChangePrizeInfo()
    {
        $id = input("post.id");
        $mark = input("post.mark");
        $storage = input("post.storage");
        $field = input("post.field");
        $new_param = input("post.new_param");
        $list = Session("prize_" . $mark);
        $list[$id][$field] = $new_param;

        Session("prize_" . $mark, $list);
//        if($storage=="DB"){
//            $db_id=input("post.db_id");
//            Db::table("active_reward")->where(array("id"=>$db_id))->update(array($field=>$new_param));
//        }
        return array("status" => true);
    }

    function setRecords()
    {
        $_sender=input("post.sender");
        $_receipter=input("post.receipter");
        $_content=input("post.content");
        $_time=time();
        $_send_name=array();
        $_receipt_name=array();
        # 查询是否存在
        $_main_inner=Db::connect("db_config2")->table("chat")
        ->where(array("main"=>$_sender,"relevance"=>$_receipter))->find();
        if(!empty($_main_inner)){

            Db::connect("db_config2")->table("chat")
                ->where(array("main"=>$_sender,"relevance"=>$_receipter))
                ->update(array("content"=>array('$push',array("timestamp"=>$_time,"text"=>$_content,"mark"=>1))));
        }else{
            $_send_name=Db::table("member")->field("name,phone,code")->where(array("id"=>$_sender))->find();
            $_receipt_name=Db::table("member")->field("name,phone,code")->where(array("id"=>$_receipter))->find();
            $_send_array=array("main"=>$_sender,"relevance"=>$_receipter,"send_name"=>$_send_name['name'],
                "send_phone"=>$_send_name['phone'],"send_code"=>$_send_name['code'],"receipt_name"=>$_receipt_name['name'],
                "receipt_phone"=>$_receipt_name['phone'],"receipt_code"=>$_receipt_name['code'],
                "content"=>array(array('text'=>$_content,"mark"=>1,"timestamp"=>$_time)));
            Db::connect("db_config2")->table("chat")->insert($_send_array);
        }
        $_receipt_inner=Db::connect("db_config2")->table("chat")
            ->where(array("main"=>$_receipter,"relevance"=>$_sender))->find();
        if(!empty($_receipt_inner)){
            Db::connect("db_config2")->table("chat")
                ->where(array("main"=>$_receipter,"relevance"=>$_sender))
                ->update(array("content"=>array('$push',array("timestamp"=>$_time,"text"=>$_content,"mark"=>2))));
        }else{
            $_receipt_array=array("main"=>$_receipter,"relevance"=>$_sender,
                "send_name"=>$_receipt_name['name'],"send_phone"=>$_receipt_name['phone'],"send_code"=>$_receipt_name['code'],
                "receipt_name"=>$_send_name['name'],"receipt_phone"=>$_send_name['phone'],"receipt_code"=>$_send_name['code'],
                "content"=>array(array('text'=>$_content,"mark"=>2,"timestamp"=>$_time)));
            Db::connect("db_config2")->table("chat")->insert($_receipt_array);
        }
        echo(true);
    }

    /**
     * 获取毫秒级别的时间戳
     */
    function getMillisecond()
    {
        //获取毫秒的时间戳
        $time = explode(" ", microtime());
        $time = $time[1] . ($time[0] * 1000);
        $time2 = explode(".", $time);
        $time = $time2[0];
        return $time;
    }
}